﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.Office.Server.UserProfiles;
namespace Trig_AMJ_IT_Forms.ControlTemplates.Trig_AMJ_IT_Forms
{
    public partial class UserProfileInfo : UserControl
    {
        SPHelper obj = new SPHelper();
        string ErrorMsgs;

        public static string SiteURL { get; set; }
        public static string Mode { get; set; }
        public static string ListID { get; set; }
        public static string RefNo { get; set; }
        public static string UserName { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            ClearControls();

            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";

            Mode = Request.QueryString["Mode"];
            if (Mode == "New")
                UserName = SPContext.Current.Web.CurrentUser.LoginName;   // Get Loggedin User and set properties value to User Controls
            else
            {
                // ListID = Request.QueryString["FormID"];
                RefNo = Request.QueryString["RefID"];

                // Get Loggedin User name by using the Reference Number, also set User Name as Main List Loggedin User
                // This function is fired while the form Mode status gets Edit,View and Print. 
                SPSecurity.RunWithElevatedPrivileges(delegate() { UserName = GetRequestedByUser(SiteURL, Convert.ToString(lblFormID.Text).Trim(), RefNo); });
            }

            if (!string.IsNullOrEmpty(UserName))
                // Get User Profile information using the User Name
                SPSecurity.RunWithElevatedPrivileges(delegate() { GetCurrentUserDetails(UserName, lblEmpName, lblEmpID, lblDivision, lblDepartment, lblDesignation, ImgUser); });
        }


        private void ClearControls()
        {
            lblEmpName.Text = "";
            lblEmpID.Text = "";
            lblDivision.Text = "";
            lblDesignation.Text = "";
            ImgUser.ImageUrl = "";
        }

        #region "GetSubmittedUser"
        /// <summary>
        /// Get submitted user (Created By) from corresponding forms
        /// </summary>
        /// <param name="SiteURL"></param>
        /// <param name="listID"></param>
        /// <param name="refNo"></param>
        /// <returns></returns>
        public string GetRequestedByUser(string SiteURL, string listID, string refNo)
        {
            string requestor = null;
            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        SPList oList = oWeb.Lists[new Guid(listID)];
                        if (oList != null)
                        {
                            SPQuery qry = new SPQuery();
                            qry.Query = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
                            qry.ViewFields = "<FieldRef Name='RequestedBy' />";
                            SPListItem oLstItems = oList.GetItems(qry)[0];
                            SPFieldUserValue user = new SPFieldUserValue(SPContext.Current.Web, oLstItems["RequestedBy"].ToString());
                            requestor = user.LookupValue;

                        }
                        oWeb.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "UserProfileInfo" + " :: " + "GetSubmittedUser";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
            return requestor;
        }

        #endregion

        #region "Get User Profiles"
        /// <summary>
        /// Get current user details to update on User controls
        /// </summary>
        /// <param name="AccountName"></param>
        /// <param name="name"></param>
        /// <param name="id"></param>
        /// <param name="dept"></param>
        /// <param name="position"></param>
        /// <param name="img"></param>
        public void GetCurrentUserDetails(string AccountName, Label name, Label id, Label division, Label department, Label designation, Image img)
        {
            try
            {
                UserProfile userProfile = GetUserInfo(AccountName);
                if (userProfile[PropertyConstants.FirstName].Value != null)
                {
                    if (name != null)
                        name.Text = userProfile[PropertyConstants.FirstName].Value.ToString();
                }

                checkField(userProfile, id, "EmployeeID");
                checkField(userProfile, division, "Division");
                checkField(userProfile, department, "Department");
                checkField(userProfile, designation, "Designation");

                if (userProfile[PropertyConstants.PictureUrl].Value != null)
                {
                    img.ImageUrl = userProfile[PropertyConstants.PictureUrl].Value.ToString();

                }
                else
                    img.ImageUrl = "/_layouts/1033/IMAGES/PERSON.gif";

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "UserProfileInfo" + " :: " + "GetCurrentUserDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        private void checkField(UserProfile userProfile, Label fieldName, string propertyName)
        {
            try
            {
                if (userProfile[propertyName].Value != null)
                    fieldName.Text = userProfile[propertyName].Value.ToString();
                else
                    fieldName.Text = "NA";

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "UserProfileInfo" + " :: " + "checkField";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        private UserProfile GetUserInfo(string AccountName)
        {
            UserProfile profile = null;
            try
            {
                SPServiceContext serviceContext = SPServiceContext.Current;
                UserProfileManager profileManager = new UserProfileManager(serviceContext);
                if (AccountName != string.Empty)
                {
                    profile = profileManager.GetUserProfile(AccountName);
                }
                else
                {
                    profile = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.RawSid);
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "UserProfileInfo" + " :: " + "checkField";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
            
            return profile;
        }

        #endregion
    }

}
